<template>
	<view class="create_new_address_main">
		<view class="return-title">
			<uni-icons type="left" size="25" class="left-icon" @click="returnPreviewPage"></uni-icons>
			<text class="address-page-title">收货地址</text>
		</view>
		<!-- 自定义表单校验 -->
		<uni-forms ref="customForm" :rules="customRules" :modelValue="customFormData" :label-width="100">
			<uni-forms-item label="姓名" required name="name">
				<uni-easyinput v-model="customFormData.name" placeholder="请输入收件人姓名" />
			</uni-forms-item>
			<uni-forms-item label="电话" required name="phone">
				<uni-easyinput v-model="customFormData.phone" placeholder="请输入手机号" type="number" />
			</uni-forms-item>
			<uni-forms-item label="所在地区" required name="location" class="location_picker_form_item">
				<uni-data-picker placeholder="请选择所在地区" popup-title="请选择所在地区" :localdata="area"
					v-model="customFormData.location" @change="onchange">
				</uni-data-picker>
				<!-- <uni-icons type="location" size="24" class="location_icon" @click="getLocation"></uni-icons> -->
			</uni-forms-item>
			<uni-forms-item label="详细地址" required name="detailAdress">
				<uni-easyinput v-model="customFormData.detailAdress" placeholder="请输入详细地址" type="text" />
				<view class="detail_address_tip">街道/门牌号等</view>
			</uni-forms-item>
		</uni-forms>
		<view class="default_address_view">
			<view class="default_address_view_left">
				设置为默认地址
			</view>
			<view class="default_address_view_icon">
				<switch :checked="isDefaultAddress" color="#66596b" @click="changeSwitch" />
			</view>
		</view>
		<button type="primary" @click="submit('customForm')" class="save_btn">保存并使用</button>
	</view>
</template>

<script>
	import areaArray from '../../../common/area.js';
	import {
		addAddress,getAddressInfoByAid
	} from '@/request/user.js';
	import mitter from '@/common/mitt/eventBus.js';
	export default {
		data() {
			return {
				addressAid: 0, // 地址aid，如果是编辑，那么就为传过来的地址aid；如果是添加那么就为0
				isDefaultAddress: false, // 是否是默认地址
				area: areaArray, // 全国地区三级联动数据
				// 自定义表单数据
				customFormData: {
					name: '',
					phone: '',
					location: '浙江省/金华市/永康市',
					detailAdress: '',
				},

				selectedLocation: [], // 通过地图选择的省市县

				// 自定义表单校验规则
				customRules: {
					name: {
						rules: [{
							required: true,
							errorMessage: '收件人姓名不能为空'
						}]
					},
					phone: {
						rules: [{
								required: true,
								errorMessage: '手机号不能为空'
							},
							{
								validateFunction: function(rule, value, data, callback) {
									// 定义手机号码的正则表达式
									const phoneRegex = /^1[3-9]\d{9}$/;
									if (!phoneRegex.test(value)) {
										callback('手机号格式错误')
									}
									return true;
								}
							}
						]
					},
					location: {
						rules: [{
							required: true,
							errorMessage: '所在地区不能为空',
						}]
					},
					detailAdress: {
						rules: [{
							required: true,
							errorMessage: '详细地址不能为空',
						}]
					}
				},
			};
		},
		
		onLoad(options) {
			// console.log("地址aid： ", options);
			// 根据addressAid获取地址信息
			this.addressAid = options.addressAid;
			this.getAddressInfoByAidFunc(options.addressAid);
		},

		onReady() {
			// 设置自定义表单校验规则，必须在节点渲染完毕后执行
			this.$refs.customForm.setRules(this.customRules)
		},
		methods: {
			
			// 根据addressAid获取地址信息
			getAddressInfoByAidFunc(addressAid){
				const self = this;
				// console.log(addressAid);
				// console.log(typeof addressAid);
				if(Number(addressAid) === 0){
					// 这是添加，不用获取
					return;
				}else if(Number(addressAid) > 0){
					// 这是编辑地址，需要获取地址信息
					getAddressInfoByAid({addressAid}).then(res=>{
						// console.log(res);
						self.customFormData = res.data.data.customFormData;
						self.isDefaultAddress = res.data.data.isDefaultAddress;
					}).catch(err=>{
						console.error(err);
					})
				}
			},
			
			// getLocation() {
			// 	uni.getLocation({
			// 		type: 'gcj02',
			// 		success: (res) => {
			// 			// 这里需要根据获取到的经纬度，调用逆地理编码接口来获取省市县信息
			// 			// 假设使用uni - reverse - geocoding - api（可能需要安装和配置）
			// 			uni.reverseGeocoding({
			// 				longitude: res.longitude,
			// 				latitude: res.latitude,
			// 				success: (reverseRes) => {
			// 					let province = reverseRes.address.province;
			// 					let city = reverseRes.address.city;
			// 					let county = reverseRes.address.district;
			// 					// 在area中查找对应的索引来设置selectedLocation
			// 					// 这部分代码可能需要根据area的具体结构来调整
			// 					let provinceIndex = this.area.findIndex(item => item.text ===
			// 						province);
			// 					let cityIndex = this.area[provinceIndex].children.findIndex(
			// 						item => item.text === city);
			// 					let countyIndex = this.area[provinceIndex].children[cityIndex]
			// 						.children.findIndex(item => item.text === county);
			// 					this.selectedLocation = [provinceIndex, cityIndex, countyIndex];
			// 				}
			// 			});
			// 		}
			// 	});
			// },
			onPickerChange(e) {
				console.log('选中的值发生变化', e);
			},

			// 表单校验
			submit(ref) {
				const self = this;
				self.$refs[ref].validate().then(res => {
					// console.log('success', res);
					const data = {
						addressAid: self.addressAid,
						...res,
						isDefault: self.isDefaultAddress
					}
					// console.log("发送到后端的数据：", data);
					addAddress(data).then(saveRes => {
						// console.log(saveRes);
						if (saveRes.data.code === 10000) {
							uni.showToast({
								title: saveRes.data.message
							})
							mitter.emit("getAddressList", true);
							setTimeout(() => {
								uni.navigateBack();
							}, 500)
						} else {
							uni.showToast({
								title: saveRes.data.message,
								icon: 'error'
							})
						}
					}).catch(err => {
						console.error(err);
						uni.showToast({
							title: `系统异常，请稍后再试...`,
							icon: 'error'
						})
					})
				}).catch(err => {
					console.log('err', err);
				})
			},

			changeSwitch() {
				this.isDefaultAddress = !this.isDefaultAddress;
			},

			onchange(e) {
				let selectAreaArr = e.detail.value;
				if (selectAreaArr.length > 0) {
					this.customFormData.location = selectAreaArr[0].text + '/' + selectAreaArr[1].text + '/' +
						selectAreaArr[2].text
					console.log(this.customFormData.location);
				}
			},

			returnPreviewPage() {
				uni.navigateBack()
			},
		},
	};
</script>

<style scoped>
	.create_new_address_main {
		padding: 30rpx;
	}

	.save_btn {
		margin-top: 40rpx;
		background-color: #66596b;
		border-radius: 70rpx;
	}

	.location_picker_form_item {
		position: relative;
	}

	.location_icon {
		position: absolute;
		bottom: 10rpx;
		right: 60rpx;
	}

	.detail_address_tip {
		margin-top: 10rpx;
		font-size: 20rpx;
		color: #7e7e7e;
	}

	.default_address_view {
		display: flex;
		justify-content: space-between;
	}

	.default_address_view_left {
		font-size: 28rpx;
		color: #505050;
		align-items: center;
		display: flex;
		justify-content: center;
	}

	.return-title {
		text-align: center;
		margin-top: 60rpx;
		margin-bottom: 60rpx;
		position: relative;
	}

	.address-page-title {
		font-size: 34rpx;
	}

	.left-icon {
		position: absolute;
		left: 0;
	}
</style>